<template>
  <div :class="['register', { mobile: $isMobile }]">
    <div class="head flexcc" @click="openUrl('/')">
      <img v-if="!$isMobile" src="@/assets/img/logo.png" alt="" />
      <img v-else src="@/assets/img/fleetmanagers.net_2.png" alt="" />
    </div>
    <div class="flexcs-col">
      <div class="con">
        <div class="title flexcc">{{ t('register.title') }}</div>
        <el-form class="mt-3" ref="formEl" label-position="top" :model="formData" :rules="rules">
          <el-row class="row">
            <el-col :span="24">
              <el-form-item prop="realName">
                <el-input v-model="formData.realName" :placeholder="t('register.r1_1')" class="input"
                  maxlength="40"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="phoneNumber">
                <el-input v-model="formData.phoneNumber" :placeholder="t('register.r1_2')" class="input"
                  type="number"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="email">
                <el-input v-model="formData.email" :placeholder="t('register.r1_3')" class="input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="enterpriseName">
                <el-autocomplete class="wp-100" v-model="formData.enterpriseName" :fetch-suggestions="querySearch"
                  clearable :placeholder="t('register.r1_4')" placeholder="Please Input" :maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col class="grid mo1">
              <el-form-item>
                <el-select v-model="continentValue" :placeholder="t('register.r1_6')" class="select" clearable filterable>
                  <el-option v-for="(item, index) in continentOptionList" :key="index" :value="item.continentCode"
                    :label="item.continentName">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="countryId">
                <el-select v-model="formData.countryId" :placeholder="t('register.r1_5')" class="select"
                  :disabled="!continentValue" clearable filterable>
                  <el-option v-for="(item, index) in countryOptionList" :key="index" :value="item.id"
                    :label="item.countryName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="registerClassId">
                <el-select v-model="formData.registerClassId" :placeholder="t('register.r1_9')" class="select" clearable>
                  <el-option v-for="(item, index) in registerClassOption" :key="index" :value="item.id"
                    :label="item.customerClass" class="option">
                    <div v-if="item.content" class="tips">
                      <span>{{ item.customerClass }}</span>
                      <el-tooltip :content="item.content" placement="top">
                        <span>
                          <el-icon>
                            <QuestionFilled />
                          </el-icon>
                        </span>
                      </el-tooltip>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-form-item class="row radio_group" prop="registerClassId">
                        <el-radio v-model="formData.registerClassId" :label="item.id" :style="`min-width:${item.width}px;margin-right:${item.noneMr?'0px':'16px'}`"
                            v-for="(item,index) in registerClassOption" :key="index" class="item" >{{t(item.txt) }}
                            <el-tooltip :content="item.content" placement="top" v-if="item.isTip">
                                <div style="float:right ; width:16px;height: 16px;border-radius: 10px; background-color: #9D9FA5;margin-left: 8px;margin-top:8px"></div>
                            </el-tooltip>
                        </el-radio>
                    </el-form-item> -->
          <el-row class="row">
            <el-col :span="24">
              <el-form-item prop="passWord">
                <el-input v-model="formData.passWord" :placeholder="t('register.r1_7')" class="input"
                  type="password" show-password @input="formData.passWord = formData.passWord.replace(/[\u4E00-\u9FA5]/g,'')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="grid">
            <el-form-item prop="code">
              <el-input v-model="formData.code" :placeholder="t('register.r1_8')"></el-input>
            </el-form-item>
            <el-button @click="getCodeFn" type="primary" style="width: 120px;height: 45px;" :disabled="codeDis">{{ t('register.r1_10') }}</el-button>
            <!-- <img :src="codeImgUrl" style="height: 43px; cursor: pointer" @click="getCaptchaImage" /> -->
          </div>

          <el-form-item prop="agreement1" class="mt-5">
            <el-checkbox v-model="formData.agreement1">{{ t('register.r3_1') }}
              <a :href="agreementUrl + '?type=1'" style="color: #3376e5" target="_blank">{{ t('register.r3_2') }}</a>{{ t('register.r3_3') }}<a :href="agreementUrl + '?type=2'" style="color: #3376e5" target="_blank">{{ t('register.r3_4') }}</a>
            </el-checkbox>
          </el-form-item>
          <div class="flexcc mt-7">
            <el-button class="btn" @click="registerSub" type="primary">{{ t('register.r4_1') }}</el-button>
          </div>
        </el-form>
      </div>
    </div>
    <Footer />
  </div>
</template>
<script setup>
import { onMounted, ref, watch, reactive, getCurrentInstance } from 'vue'
import Footer from '@/views/layout/Footer.vue'
import { useI18n } from 'vue-i18n'
import { registerApi, listOption, captchaImage, getEnterpriseList,getCode } from '@/service/login.js'
import { countryListApi } from '@/service/common.js'
import router from '@/router'
import useLogin from '@/stores/login'
import { openUrl } from '@/utils'

const { $isMobile } = getCurrentInstance().appContext.config.globalProperties
const { setLoginDialog } = useLogin()

const { t, locale } = useI18n()
onMounted(() => {
  init()
})

const copyData = ref([]) //备份数据
const agreementUrl = window.location.href.slice(0, window.location.href.lastIndexOf('/') + 1) + 'agreement'

const continentValue = ref('') //大洲绑定
watch(continentValue, (val, old) => {
  if (val) {
    let filterArr = copyData.value
    countryOptionList.value = filterArr.filter((item) => {
      if (val == item.continentCode) {
        return item
      }
    })
    formData.value.countryId = undefined
  } else {
    formData.value.countryId = undefined
    countryOptionList.value = copyData.value
  }
})

// 提交
const loading = ref(false)
const formEl = ref(null)
const registerSub = () => {
  if (!formEl.value) return
  formEl.value.validate((valid, fields) => {
    if (valid) {
      registerApi(formData.value).then(() => {
        const customerClassCode = registerClassOption.value.find((item) => item.id === formData.value.registerClassId)?.customerClassCode
        const msg = !['20', '21', '15'].includes(customerClassCode) ? t('register.r4_2') : t('register.m2')

        ElMessageBox.alert(msg, '', {
          confirmButtonText: t('register.b1'),
          callback: (action) => {
            if ($isMobile) {
              openUrl('/login')
            } else {
              openUrl('/')
              setLoginDialog(true)
            }
          }
        })
      })
      getCaptchaImage()
    }
  })
}

//获取国家下拉
const countryOptionList = ref([]) //国家下拉
const continentOptionList = ref([]) //大洲下拉
const getCountry = () => {
  countryListApi().then((res) => {
    countryOptionList.value = res.data
    res.data.map((item) => {
      if (!continentOptionList.value.some((child) => child.continentName === item.continentName)) {
        continentOptionList.value.push(item)
      }
    })
    copyData.value = res.data
  })
}

//获取身份选择
const registerClassOption = ref([]) //身份类型
const getRegisterClass = () => {
  listOption().then(({ data }) => {
    const obj = {
      '09': t('register.c_09'),
      11: t('register.c_11')
    }

    data.forEach((item) => {
      if (obj[item.customerClassCode]) {
        item.content = obj[item.customerClassCode]
      }
    })

    registerClassOption.value = data
  })
}

//获取验证码
const codeImgUrl = ref('') //验证码
const getCaptchaImage = () => {
  captchaImage().then((res) => {
    codeImgUrl.value = 'data:image/png;base64,' + res.img
    formData.value.uuid = res.uuid
  })
}

const formData = ref({
  realName: '',
  phoneNumber: '',
  email: '',
  enterpriseName: '',
  countryId: '',
  registerClassId: '',
  passWord: '',
  countryId: '',
  uuid: ''
})
watch(
  () => formData.value.registerClassId,
  (n) => {
    const customerClassCode = registerClassOption.value.find((item) => item.id === n)?.customerClassCode
    rules.value.enterpriseName[0].required = !['20', '21', '15'].includes(customerClassCode)
  }
)

//  验证邮箱的正则表达式
const checkEmail = (r, value, cb) => {
  const regEmail = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
  if (regEmail.test(formData.value.email)) {
    // // 合法邮箱
    return cb()
    // return;
  }
  cb(new Error(t('passwordRecovery.r2-2')))
}
const inputPsw = (r, value, cb) => {
  const reg = /^(?![^a-zA-Z]+$)(?!\D+$).{6,30}$/
  if (reg.test(formData.value.passWord)) {
    // 合法邮箱
    return cb()
    // return;
  }
  cb(new Error(t('passwordRecovery.r4_1')))
}
const checkAgreement = (r, value, cb) => {
  if (!value) {
    return cb(new Error(t('register.r3_1')))
  }
  cb()
}
const rules = ref({
  realName: [{ required: true, message: t('register.r1_1'), trigger: 'change' }],
  phoneNumber: [{ required: true, message: t('register.r1_2'), trigger: 'change' }],
  email: [{ required: true, validator: checkEmail, trigger: 'blur' }],
  enterpriseName: [{ required: true, message: t('register.r1_4'), trigger: 'blur' }],
  countryId: [{ required: true, message: t('register.r1_5'), trigger: 'change' }],
  registerClassId: [{ required: true, message: t('register.r1_9'), trigger: 'change' }],
  passWord: [{ required: true, validator: inputPsw, trigger: 'blur' }],
  code: [{ required: true, message: t('register.r1_8'), trigger: 'change' }],
  agreement1: [{ required: true, validator: checkAgreement, trigger: 'change' }],
  // agreement2: [{ required: true, validator: checkAgreement, trigger: 'change' }]
})

// 企业信息
const querySearch = (queryString, cb) => {
  getEnterpriseList({ name: queryString }).then(({ data }) => {
    cb(
      data.map((item) => {
        return {
          value: item,
          label: item
        }
      })
    )
  })
}
const codeDis=ref(false)
const getCodeFn=()=>{
  if(!formData.value.email||!formData.value.realName){
    ElMessage.warning(t('register.r4_3'))
    return false
  }
  codeDis.value=true
  getCode({email:formData.value.email,userName:formData.value.realName}).then(res=>{
    ElMessage.success(t('register.r4_4'))
    formData.value.uuid=res.uuid
    codeDis.value=false
  })
}

//
const init = () => {
  getCaptchaImage()
  getCountry()
  getRegisterClass()
}
</script>
<style scoped lang="scss">
.register {
  background: #f5f5f5;
  --el-component-size: 45px;
  --el-color-primary: var(--titleColor);
  --el-text-color-regular: var(--titleColor);
  --el-color-primary-light-3: var(--titleColor);
  --el-color-primary-dark-2: #000;

  .pointer {
    cursor: pointer;
  }

  .head {
    height: 108px;
    border-bottom: 6px solid var(--titleColor);

    img {
      height: 64px;
    }
  }

  .title {
    font-size: 30px;
    font-weight: bold;
  }

  .con {
    width: 600px;
    padding: 70px 0 0;

    .row {
      margin: auto;
    }

    .radio_group {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 60px;

      // justify-content: space-between;
      .item {
        height: 50px;
        background: white;
        border-radius: 5px;
        margin-bottom: 30px;
        padding: 18px 0px;
        font-size: 12px;
        padding-left: 10px;
        color: #6a6973;

        :deep(.el-radio__label) {
          display: flex;
          flex: 1;
          justify-content: space-between;
          padding-right: 10px;
        }

        :deep(.is-checked .el-radio__inner) {
          border-color: #ca2a02;
          background: #ca2a02;
        }

        :deep(.is-checked .el-radio__label) {
          color: #6a6973;
        }
      }
    }

    .grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
    }

    .el-col {
      margin-bottom: 10px;
    }

    .input {
      height: 46px;
    }

    .select {
      width: 100%;
    }

    .btn {
      width: 260px;
      height: 46px;
    }
  }

  &.mobile {
    background: #fff url('@/assets/img/pic.png') no-repeat 0 bottom;

    .head {
      height: 50px;
      background: var(--mainColor);
      color: #fff;
      border-bottom: 0;

      img {
        height: 20px;
      }
    }

    .con {
      width: 380px;
      padding: 20px;
    }

    .mo1 {
      display: block;
    }
  }
}

.tips {
  display: flex;
  width: 100%;
  justify-content: space-between;

  .el-icon {
    width: 18px;
    height: 18px;

    svg {
      width: 18px;
      height: 18px;
    }
  }
}
</style>
